﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 球队用户服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppUserTeamService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppUserTeam> _appUserTeamRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly AppTeamPlayerApplyService _appTeamPlayerApplyService;
    private readonly UserManager _userManager;

    public AppUserTeamService(SqlSugarRepository<AppUserTeam> appUserTeamRep, ISqlSugarClient sqlSugarClient, AppTeamPlayerApplyService appTeamPlayerApplyService, UserManager userManager)
    {
        _appUserTeamRep = appUserTeamRep;
        _sqlSugarClient = sqlSugarClient;
        _appTeamPlayerApplyService = appTeamPlayerApplyService;
        _userManager = userManager;
    }

    /// <summary>
    /// 分页查询球队用户 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询球队用户")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppUserTeamOutput>> Page(PageAppUserTeamInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appUserTeamRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.UserId != null, u => u.UserId == input.UserId)
            .WhereIF(input.TeamId != null, u => u.TeamId == input.TeamId)
            .WhereIF(input.Role.HasValue, u => u.Role == input.Role)
            .WhereIF(input.Position.HasValue, u => u.Position == input.Position)
            .WhereIF(input.JoinDateRange?.Length == 2, u => u.JoinDate >= input.JoinDateRange[0] && u.JoinDate <= input.JoinDateRange[1])
            .WhereIF(input.Status.HasValue, u => u.Status == input.Status)
            .LeftJoin<SysUser>((u, user) => u.UserId == user.Id)
            .LeftJoin<AppTeam>((u, user, team) => u.TeamId == team.Id)
            .Select((u, user, team) => new AppUserTeamOutput
            {
                Id = u.Id,
                UserId = u.UserId,
                UserFkDisplayName = $"{user.RealName}",
                TeamId = u.TeamId,
                TeamFkDisplayName = $"{team.Name}",
                Role = u.Role,
                Position = u.Position,
                JoinDate = u.JoinDate,
                Status = u.Status,
                Remark = u.Remark,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取球队用户详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取球队用户详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppUserTeam> Detail([FromQuery] QueryByIdAppUserTeamInput input)
    {
        return await _appUserTeamRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加球队用户 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加球队用户")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppUserTeamInput input)
    {
        if (await _appUserTeamRep.IsAnyAsync(u => u.UserId == input.UserId && u.TeamId == input.TeamId)) throw Oops.Oh("请勿重复申请");
        var entity = input.Adapt<AppUserTeam>();
        //增加申请表
        await _appTeamPlayerApplyService.Add(new AddAppTeamPlayerApplyInput
        {
            Type = TeamPlayerEnum.Team,
            UserId = _userManager.UserId,
            TeamId = input.TeamId,
            ApplicationDate = DateTime.Now,
        });
        return await _appUserTeamRep.InsertAsync(entity) ? entity.Id : 0;

    }

    /// <summary>
    /// 更新球队用户 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新球队用户")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppUserTeamInput input)
    {
        var entity = input.Adapt<AppUserTeam>();
        await _appUserTeamRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除球队用户 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除球队用户")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppUserTeamInput input)
    {
        var entity = await _appUserTeamRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appUserTeamRep.FakeDeleteAsync(entity);   //假删除
        //await _appUserTeamRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除球队用户 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除球队用户")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppUserTeamInput> input)
    {
        var exp = Expressionable.Create<AppUserTeam>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appUserTeamRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appUserTeamRep.FakeDeleteAsync(list);   //假删除
        //return await _appUserTeamRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 设置球队用户状态 🚫
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("设置球队用户状态")]
    [ApiDescriptionSettings(Name = "SetStatus"), HttpPost]
    public async Task SetAppUserTeamStatus(SetAppUserTeamStatusInput input)
    {
        await _appUserTeamRep.AsUpdateable().SetColumns(u => u.Status, input.Status).Where(u => u.Id == input.Id).ExecuteCommandAsync();
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppUserTeamInput input)
    {
        var userIdData = await _appUserTeamRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppUserTeam>(input.FromPage, (u, r) => u.Id == r.UserId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        var teamIdData = await _appUserTeamRep.Context.Queryable<AppTeam>()
            .InnerJoinIF<AppUserTeam>(input.FromPage, (u, r) => u.Id == r.TeamId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.Name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "userId", userIdData },
            { "teamId", teamIdData },
        };
    }
    
    /// <summary>
    /// 导出球队用户记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出球队用户记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppUserTeamInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppUserTeamOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "球队用户导出记录");
    }
    
    /// <summary>
    /// 下载球队用户数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载球队用户数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppUserTeamOutput>(), "球队用户导入模板", (_, info) =>
        {
            if (nameof(ExportAppUserTeamOutput.UserFkDisplayName) == info.Name) return _appUserTeamRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            if (nameof(ExportAppUserTeamOutput.TeamFkDisplayName) == info.Name) return _appUserTeamRep.Context.Queryable<AppTeam>().Select(u => $"{u.Name}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入球队用户记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入球队用户记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppUserTeamInput, AppUserTeam>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 用户
                    var userIdLabelList = pageItems.Where(x => x.UserFkDisplayName != null).Select(x => x.UserFkDisplayName).Distinct().ToList();
                    if (userIdLabelList.Any()) {
                        var userIdLinkMap = _appUserTeamRep.Context.Queryable<SysUser>().Where(u => userIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.UserId = userIdLinkMap.GetValueOrDefault(e.UserFkDisplayName ?? "");
                            if (e.UserId == null) e.Error = "用户链接失败";
                        });
                    }
                    // 链接 球队
                    var teamIdLabelList = pageItems.Where(x => x.TeamFkDisplayName != null).Select(x => x.TeamFkDisplayName).Distinct().ToList();
                    if (teamIdLabelList.Any()) {
                        var teamIdLinkMap = _appUserTeamRep.Context.Queryable<AppTeam>().Where(u => teamIdLabelList.Contains($"{u.Name}")).ToList().ToDictionary(u => $"{u.Name}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.TeamId = teamIdLinkMap.GetValueOrDefault(e.TeamFkDisplayName ?? "");
                            if (e.TeamId == null) e.Error = "球队链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.UserId == null){
                            x.Error = "用户不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.TeamId == null){
                            x.Error = "球队不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Role == null){
                            x.Error = "角色不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Status == null){
                            x.Error = "状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppUserTeam>>();
                    
                    var storageable = _appUserTeamRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.Remark?.Length > 256, "备注长度不能超过256个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }

    /// <summary>
    /// 设置球队用户角色为管理员 🚫
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("设置球队用户角色为管理员")]
    [ApiDescriptionSettings(Name = "SetRole"), HttpPost]
    public async Task SetAppUserTeamRole(SetAppUserTeamRolesInput input)
    {
        await _appUserTeamRep.AsUpdateable().SetColumns(u => u.Role, input.Role).Where(u => u.Id == input.Id && u.UserId==input.UserId).ExecuteCommandAsync();
    }
}
